package com.zwh.spring.demo.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@MapperScan(basePackages= {"com.zwh.spring.demo.mapper.secondary"}, sqlSessionFactoryRef="secondarySessionFactory")
public class MyBatisSecondaryConfig {

	@Autowired
	@Qualifier("secondaryDataSource")
	private DataSource secondaryDataSource;
	
	@Bean
	public SqlSessionFactory secondarySessionFactory() throws Exception{
		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		factoryBean.setDataSource(secondaryDataSource);
		
		return factoryBean.getObject();
	}
	
	@Bean
	public SqlSessionTemplate secondarySessionTemplate() throws Exception{
		SqlSessionTemplate template = new SqlSessionTemplate(secondarySessionFactory());
		
		return template;
		
	}
	
	@Bean(name="secondaryTransectionManager")
	public DataSourceTransactionManager transactionManagers() {
		return new DataSourceTransactionManager(secondaryDataSource);
	}
}
